import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/config/app.enum.dart';
import 'package:interview/utils/http.dart';
import 'package:interview/utils/logger.dart';


/// Question 数据模型
class Question {
  final String id;
  String stem; // 题干
  final int difficulty; // 难度
  RxInt likeCount; // 点赞数  
  RxInt views; // 浏览数
  final int readFlag; // 是否已看 (0 或 1)
  String? content; // 面经有 试题没有
  String? createdAt;
  String? creatorAvatar;
  int? questionType;
  String? subjectName;
  String? creatorName;

  Question({
    required this.id,
    required this.stem,
    required this.difficulty,
    required RxInt likeCount,
    required RxInt views,
    required this.readFlag,
    this.content,
    this.createdAt,
    this.creatorAvatar,
    this.questionType,
    this.subjectName,
    this.creatorName
  }):  likeCount = likeCount, views = views;

  // JSON 转换
  factory Question.fromJson(Map<String, dynamic> json) {
    return Question(
      id: json['id'] is int ? json['id'].toString() : json['id'] as String,
      stem: json['stem'] as String,
      difficulty: json['difficulty'] as int,
      likeCount: (json['likeCount'] as int).obs,
      views: (json['views'] as int).obs,
      readFlag: json["readFlag"] == null ? 0 : json['readFlag'] as int,
      createdAt:json["createdAt"] as String,
      creatorAvatar:json["creatorAvatar"] as String,
      questionType:json["questionType"] as int,
      content: json["content"] == null ? "暂无" : json["content"] as String ,
      subjectName:json["subjectName"] == null ? "学科" :json["subjectName"] as String,
      creatorName: json["creatorName"] == null ? "匿名用户" : json["creatorName"] as String,
    );
  }
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'stem': stem,
      'difficulty': difficulty,
      'likeCount': likeCount.value,
      'views': views.value,
      'readFlag': readFlag,
      'createdAt':createdAt,
      'creatorAvatar':creatorAvatar,
      'questionType':questionType,
      'content':content,
      'subjectName':subjectName,
      'creatorName':creatorName
    };
  }
}



/// QuestionListParams 请求参数封装
class QuestionListParams {
  final int? type;
  final int? questionBankType;
  final int? sort; // 对应 SortType 的 index
  final int? page;
  final int? pageSize;
  final String? keyword;

  QuestionListParams({
    this.type,
    this.questionBankType,
    this.sort = AppEnumSortType.sortDefault,
    this.page,
    this.pageSize,
    this.keyword
  });
  /// 转换为请求参数的 Map
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> params = {
      'type': type,
      'questionBankType': questionBankType ?? 10,
      'sort': sort,
      'page': page ?? 1,
      'pageSize': pageSize ?? 10,
      'keyword': keyword,
    };

    // 移除值为 null 的参数
    params.removeWhere((key, value) => value == null);

    return params;
  }
}

/// QuestionList响应数据封装
class QuestionListResponse {
  final List<Question> questions;
  final int total;
  final int pageTotal;

  QuestionListResponse({
    required this.questions,
    required this.total,
    required this.pageTotal,
  });
}


/// 获取QuestionList
Future<QuestionListResponse> fetchQuestionList(QuestionListParams params , BuildContext context) async {
  try {
    // 发起 GET 请求
    final response = await Http.get<Map<String, dynamic>>('question/list', queryParameters: params.toJson() , context: context);
    // 检查响应结构
    if (response['success'] == true && response['data'] is Map<String, dynamic>) {
      final data = response['data'] as Map<String, dynamic>;
     // 验证和提取数据
      if (data['rows'] is List && data['total'] is int && data['pageTotal'] is int) {
        final questions = (data['rows'] as List).map((item) => Question.fromJson(item as Map<String, dynamic>)).toList();
        final total = data['total'] as int;
        final pageTotal = data['pageTotal'] as int;
        // 返回封装的结果
        return QuestionListResponse(
          questions: questions,
          total: total,
          pageTotal: pageTotal,
        );
      } else {
        throw Exception('QuestionList数据格式错误: 缺少 total/pageTotal 或 rows 字段格式不正确');
      }
    } else {
      throw Exception('响应数据格式错误或未成功: ${response['message']}');
    }
  } catch (e) {
    // 错误处理
    Logger.error("获取QuestionList失败: $e", tag: 'fetchQuestionList');
    throw Exception('获取QuestionList失败: $e');
  }
}


